package com.atguigu.gulimall.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.SkuElasticSearchModleTO;
import com.atguigu.gulimall.search.config.GulimallElasticSearchConfig;
import com.atguigu.gulimall.search.constant.EsConstant;
import com.atguigu.gulimall.search.service.ProductService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    /**
     * 商品上架保存数据到ES中
     *
     * @param searchModleTOS*/
    @Override
    public Boolean productStatusUp(List<SkuElasticSearchModleTO> searchModleTOS) {

        //保存数据到ES
        //1: 给ES建立索引,建立好映射关系(mapping)
        //2: 给ES中保存这些数据
        //批量保存需要传BulkRequest,option这两个参数
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuElasticSearchModleTO modleTO : searchModleTOS) {
            //构造保存请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(modleTO.getSkuId().toString());
            String modle = JSON.toJSONString(modleTO);
            indexRequest.source(modle);
            bulkRequest.add(indexRequest);
        }
        try {
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, GulimallElasticSearchConfig.COMMON_OPTIONS);
            //TODO 批量保存的时候出现错误的处理情况
            boolean failures = bulk.hasFailures();
            List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("保存完成的skuID是:{}",collect);
            return failures;
        } catch (IOException e) {
            log.error("保存数据到ES发生异常,原因是:{}",e);
        }
        return false;
    }
}
